package com.itzyf.pokemondata.activity.gallery

import android.content.Intent
import android.graphics.Color
import android.graphics.Typeface
import android.text.TextUtils
import android.view.inputmethod.EditorInfo
import android.widget.TextView
import androidx.recyclerview.widget.LinearLayoutManager
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.BaseViewHolder
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import com.itzyf.pokemondata.R
import com.itzyf.pokemondata.bean.CTypeDo
import com.itzyf.pokemondata.bean.DbComprehensiveDo
import com.itzyf.pokemondata.bean.DbComprehensiveTypeDo
import com.tydic.baselibrary.activity.BaseActivity
import kotlinx.android.synthetic.main.activity_new_gallery.*
import org.litepal.LitePal

class NewGalleryActivity : BaseActivity() {
    var mTypeDatas: MutableList<DbComprehensiveTypeDo?> = ArrayList()
    private lateinit var mTypeAdapter: QuickTypeAdapter
    override fun getContentViewId() = R.layout.activity_new_gallery

    override fun getToolbarTitle() = "综合大全"

    //以下是右侧
    var mDatas: MutableList<GalleryDo?> = ArrayList()
    private lateinit var mAdapter: QuickAdapter
    var index = 0

    var objTypeId = "5c4b0e9e9f5454004702aa95"

    override fun handlerActivity() {
        initLeft()
        initRight()

    }

    private fun initLeft() {
        mTypeAdapter = QuickTypeAdapter(R.layout.item_text3, mTypeDatas)
        rv_list1.adapter = mTypeAdapter
        rv_list1.layoutManager = LinearLayoutManager(this)
        mTypeAdapter.setOnItemClickListener { _, _, position ->
            mTypeDatas.forEachIndexed { index, item ->
                item?.isCheck = (index == position)
            }
            objTypeId = mTypeDatas[position]!!.objectId
            mTypeAdapter.notifyDataSetChanged()
            queryDatas(index = 0)
        }

        queryTypeDatas()
    }


    private fun initRight() {
        mAdapter = QuickAdapter(R.layout.item_text, mDatas)
        rv_list2.adapter = mAdapter

        rv_list2.layoutManager = LinearLayoutManager(this)
        mAdapter.setOnLoadMoreListener({ queryDatas(index++) }, rv_list2)

        mBtnSearch.setOnClickListener {
            val query = mSearchView.text.toString()
            queryDatas(query = query)
        }
        mSearchView.setOnEditorActionListener(TextView.OnEditorActionListener { _, actionId, _ ->
            if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                val query = mSearchView.text.toString()
                queryDatas(query = query)
                return@OnEditorActionListener true
            }
            false
        })
        mAdapter.setOnItemClickListener { _, _, position ->
            when (mDatas[position]!!.type) {
                0 -> {
                    val intent = Intent(this@NewGalleryActivity, ImageZoomActivity::class.java)
                    intent.putExtra("image", mDatas[position]!!.image)
                    intent.putExtra("title", mDatas[position]!!.title)
                    startActivity(intent)
                }
                1 -> {
                    val intent = Intent(this@NewGalleryActivity, MarkdownActivity::class.java)
                    intent.putExtra("objId", mDatas[position]!!.objectId)
                    intent.putExtra("title", mDatas[position]!!.title)
                    startActivity(intent)
                }
                2,4 -> {
                    val intent = Intent(this@NewGalleryActivity, WebViewActivity::class.java)
                    intent.putExtra("httpUrl", mDatas[position]!!.httpUrl)
                    intent.putExtra("title", mDatas[position]!!.title)
                    startActivity(intent)
                }
                3 -> {
                    val intent = Intent(this@NewGalleryActivity, GifActivity::class.java)
                    intent.putExtra("image", mDatas[position]!!.image)
                    intent.putExtra("title", mDatas[position]!!.title)
                    startActivity(intent)
                }
                else -> {
                    showToast("当前版本不支持，请升级")
                }
            }
        }
        queryDatas()
    }

    /**
     * 查询分类数据
     */
    private fun queryTypeDatas() {
        val dataList =
            LitePal
                .order("createdAt asc")
                .find(DbComprehensiveTypeDo::class.java)

        if (dataList != null && dataList.size > 0) {
            mTypeDatas.addAll(dataList)
        } else {
            val pokemonList = readJson<List<CTypeDo>>()
            for (poke in pokemonList) {
                mTypeDatas.add(DbComprehensiveTypeDo(poke))
            }
        }
        mTypeDatas[0]?.isCheck = true
        mTypeAdapter.notifyDataSetChanged()
    }

    /**
     * 查询数据
     */
    fun queryDatas(index: Int = 0, pageSize: Int = 20, query: String = "") {
        var where = ""
        if (!TextUtils.isEmpty(query)) {
            where = "and name like '%$query%'"
        }
        val dataList =
            LitePal
                .select("name", "imageUrl", "type", "httpUrl", "objectId")
                .limit(pageSize)
                .offset(index * pageSize)
                .order("createdAt desc")
                .where("cTypeId = ? $where", objTypeId)
                .find(DbComprehensiveDo::class.java)

        if (index == 0) {
            mDatas.clear()
        }
        for (obj in dataList) {
            mDatas.add(
                GalleryDo(
                    obj.name,
                    obj.imageUrl,
                    obj.httpUrl,
                    obj.type,
                    obj.objectId
                )
            )
        }

        if (dataList.size < pageSize) {
            mAdapter.loadMoreEnd()
        } else {
            mAdapter.loadMoreComplete()
        }
        mAdapter.notifyDataSetChanged()
    }

    private fun <T> readJson(): T {
        val stream = resources.openRawResource(R.raw.comprehensive_type)
        return stream.buffered().reader().use { reader ->
            Gson().fromJson(
                reader.readText(),
                object : TypeToken<List<CTypeDo>>() {}.type
            )
        }
    }

    internal inner class QuickTypeAdapter(layoutResId: Int, data: List<DbComprehensiveTypeDo?>) :
        BaseQuickAdapter<DbComprehensiveTypeDo, BaseViewHolder>(layoutResId, data) {

        override fun convert(helper: BaseViewHolder, item: DbComprehensiveTypeDo?) {
            helper.setText(R.id.text, item?.name)
            val textView = helper.getView<TextView>(R.id.text)
            item?.let {
                if (item.isCheck) {
                    helper.setTextColor(R.id.text, resources.getColor(R.color.colorPrimary))
                    textView.typeface = Typeface.DEFAULT_BOLD
                    helper.setBackgroundRes(R.id.root, R.color.white)
                    helper.setBackgroundRes(R.id.left, R.color.colorPrimary)
                } else {
                    helper.setTextColor(
                        R.id.text,
                        resources.getColor(R.color.qmui_config_color_black)
                    )
                    textView.typeface = Typeface.DEFAULT
                    helper.setBackgroundRes(R.id.root, R.color.bg1)
                    helper.setBackgroundRes(R.id.left, R.color.bg1)
                }
            }

        }
    }


    internal inner class QuickAdapter(layoutResId: Int, data: List<GalleryDo?>) :
        BaseQuickAdapter<GalleryDo, BaseViewHolder>(layoutResId, data) {

        override fun convert(helper: BaseViewHolder, item: GalleryDo?) {
            helper.setText(R.id.text, item?.title)
        }
    }

    data class GalleryDo(
        val title: String,
        val image: String?,
        val httpUrl: String?,
        val type: Int,
        val objectId: String
    )
}